﻿#@ ubuntu 10.10
#http://code.google.com/p/pyffmpeg/downloads/detail?name=pyffmpeg-2.1beta.linux-x86_64.tar.gz&can=2&q=
#tar xzf pyffmpeg-2.1beta.linux-x86_64.tar.gz
#sudo cp -R ./usr/ /
#sudo mount -t vboxsf [VirtualBox에서 설정한 공유폴더 이름] [마운트할 폴더]
#sudo mkdir /t
#sudo mount -t vboxsf t /t

#sudo apt-get ffmpeg
import os
from datetime import timedelta
from PIL import Image
import pyffmpeg as pf
import interval_for_thumb
SIZE_THUMB = (128,128)

def _save_thumb(im, szpath):
    im = im.copy()
    im.thumbnail(SIZE_THUMB, Image.ANTIALIAS)
    im.save(szpath)

class Thumb:
    def __init__(self,nsec,szpath):
        self.nsec = nsec
        self.szpath = szpath
    def __repr__(self):
        return '<Thumb szpath=%(szpath)s,sec=%(nsec)d>'%dict(szpath=self.szpath, nsec=self.nsec)

def get(szdir_base, szsrc, szdir_thumb, nthumb_max):

    szsrc_full = os.path.join(szdir_base,szsrc)
    szdir_thumb_full = os.path.join(szdir_base,szdir_thumb)

    v = pf.VideoStream()
    v.open(szsrc_full)
    track = v.tv
    mpegreader = v.vr
    ntime = mpegreader.duration_time()
    ntime = int(ntime)    
    ninterval = interval_for_thumb.interval_for_thumb(ntime, nthumb_max)
    try:
        os.makedirs(szdir_thumb_full)
    except:
        pass    
    l_thumb = []
    for nsec in range(0,ntime,ninterval):
        track.seek_to_seconds(nsec)
        sztime = str(timedelta(seconds=nsec))
        
        szpath = '%(szdir_thumb)s/0%(sztime)s.jpg'%locals()
        szpath = szpath.replace(':','_')
        
        l_thumb.append(Thumb(nsec,szpath))
        
        szpath_full = os.path.join(szdir_base,szpath)
        im = v.GetCurrentFrame(0)        
        _save_thumb(im, szpath_full)
    return l_thumb

if __name__ == '__main__':
    szdir_base = '/t'    
    szsrc = 'in/clock.avi'
    szdir_thumb = 'out/we/thumb'
    nthumb_max = 100    
    l_thumb = get(szdir_base, szsrc, szdir_thumb, nthumb_max)
    print l_thumb[0:3]